import taskService from "@/api/services/taskService";
import systemUserService from "@/api/services/systemUserService";
import { PlusOutlined } from "@ant-design/icons";
import {
	Checkbox,
	DatePicker,
	Form,
	Input,
	InputNumber,
	Modal,
	Select,
	Space,
	Tabs,
	Upload,
} from "antd";
import { message } from "antd";
import type { RcFile, UploadProps } from "antd/es/upload";
import type { UploadFile } from "antd/es/upload/interface";
import { useEffect, useState } from "react";
import FormBuilder, { type FormField } from "./form-builder";
import Editor from "@/components/editor";
import { UploadBox } from "@/components/upload/upload-box";

interface TaskModalProps {
	open: boolean;
	title: string;
	initialValues?: any;
	onOk: (values: any) => void;
	onCancel: () => void;
}

const { TextArea } = Input;

const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = (error) => reject(error);
	});

export default function TaskModal({
	open,
	title,
	initialValues,
	onOk,
	onCancel,
}: TaskModalProps) {
	const [form] = Form.useForm();
	const [attachment, setAttachment] = useState<string>("");
	const [taskFields, setTaskFields] = useState<FormField[]>([
		{
			id: new Date().getTime(),
			taskId: 0,
			fieldId: new Date().getTime(),
			fieldType: "richtext",
			fieldLabel: "任务提交内容",
			required: true,
			placeholder: "请输入任务提交内容",
			sort: 0,
		},
	]);

	const [categories, setCategories] = useState<
		{ label: string; value: number }[]
	>([]);
	const [admins, setAdmins] = useState<{ label: string; value: number }[]>([]);

	// 获取任务类别列表
	const fetchCategories = async () => {
		try {
			const res = await taskService.categoryList({ page: 1, limit: 100 });
			const options = res.items.map((item) => ({
				label: item.name,
				value: item.id,
			}));
			setCategories(options);
		} catch (error) {
			console.error("获取任务类别失败:", error);
		}
	};

	// 获取审核员列表
	const fetchAdmins = async () => {
		try {
			const res = await systemUserService.userList({ page: 1, limit: 10 });
			const options = res.items.map((item) => ({
				label: item.nickname || item.username,
				value: item.id,
			}));
			setAdmins(options);
		} catch (error) {
			console.error("获取审核员列表失败:", error);
		}
	};

	useEffect(() => {
		fetchCategories();
		fetchAdmins();
	}, []);

	useEffect(() => {
		if (initialValues) {
			form.setFieldsValue(initialValues);
			setAttachment(initialValues.attachment || "");
		} else {
			form.resetFields();
			setAttachment("");
		}
	}, [initialValues, form]);

	useEffect(() => {
		if (initialValues?.taskFields) {
			setTaskFields(initialValues.taskFields);
		}
	}, [initialValues]);

	const handleOk = async () => {
		try {
			const values = await form.validateFields();
			const taskFieldsData = taskFields.map((field, index) => ({
				...field,
				taskId: initialValues?.id || 0,
				sort: index,
				createTime: field.createTime || new Date(),
				updateTime: new Date(),
			}));

			const taskData = {
				...values,
				attachment,
				taskFields: taskFieldsData,
			};
			onOk(taskData);
		} catch (error) {
			message.error(error);
		}
	};

	const handleFileChange = (url: string) => {
		setAttachment(url);
	};

	const basicFields = [
		{
			name: "title",
			label: "任务标题",
			required: true,
			component: <Input placeholder="请输入任务标题" />,
		},
		{
			name: "image",
			label: "任务图片",
			required: true,
			component: (
				<UploadBox
					maxCount={1}
					listType="picture-card"
					accept="image/*"
					onChange={(image) => {
						form.setFieldValue("image", image);
					}}
				>
					<div>
						<PlusOutlined />
						<div style={{ marginTop: 8 }}>上传图片</div>
					</div>
				</UploadBox>
			),
		},
		{
			name: "category_id",
			label: "任务类别",
			required: true,
			component: (
				<Select placeholder="请选择任务类别" options={categories} allowClear />
			),
		},
		{
			name: "auditor_id",
			label: "审核员",
			required: true,
			component: (
				<Select placeholder="请选择审核员" options={admins} allowClear />
			),
		},
		{
			name: "description",
			label: "任务描述",
			rules: [
				{
					validator: async (_, value) => {
						const attachment = form.getFieldValue("attachment");
						if (!value && !attachment) {
							throw new Error("任务描述和附件必须填写一个");
						}
					},
				},
			],
			component: (
				<Editor
					id="task-description"
					style={{ height: 100 }}
					placeholder="请输入任务描述"
					value={form.getFieldValue("description")}
				/>
			),
		},
		{
			name: "attachment",
			label: "附件",
			rules: [
				{
					validator: async (_, value) => {
						const description = form.getFieldValue("description");
						if (!value && !description) {
							throw new Error("任务描述和附件必须填写一个");
						}
					},
				},
			],
			component: <UploadBox onChange={handleFileChange} value={attachment} />,
		},
		{
			name: "price",
			label: "单价(元)",
			required: true,
			component: (
				<InputNumber
					min={0}
					precision={2}
					placeholder="请输入任务单价"
					style={{ width: "100%" }}
				/>
			),
		},
		{
			name: "status",
			label: "状态",
			required: true,
			component: (
				<Select
					placeholder="请选择任务状态"
					options={[
						{ label: "待发布", value: 0 },
						{ label: "进行中", value: 1 },
					]}
				/>
			),
		},
	];

	const items = [
		{
			key: "basic",
			label: "基本信息",
			children: (
				<Form
					form={form}
					layout="vertical"
					initialValues={{
						status: 0,
					}}
				>
					{basicFields.map((field) => (
						<Form.Item
							key={field.name}
							name={field.name}
							label={field.label}
							rules={[
								field.required && {
									required: field.required,
									message: `请输入${field.label}`,
								},
							]}
						>
							{field.component}
						</Form.Item>
					))}
				</Form>
			),
		},
		{
			key: "form",
			label: "表单配置",
			children: <FormBuilder value={taskFields} onChange={setTaskFields} />,
		},
	];

	return (
		<Modal
			open={open}
			title={title}
			width={1200}
			style={{ top: 20 }}
			bodyStyle={{ maxHeight: "calc(100vh - 200px)", overflowY: "auto" }}
			onOk={handleOk}
			onCancel={onCancel}
			destroyOnClose
		>
			<Tabs items={items} />
		</Modal>
	);
}
